package com.ky.pro.java.jvm;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName XlassLoader
 * @Description 加载resources文件夹下xlass类文件，文件编码规则为x = 255 - x
 * @Date 2021/11/6 16:33
 * @Author kevin
 **/
public class XlassLoader extends ClassLoader {

    public static final String CLASS_FILE_SUFFIX = ".xlass";

    public XlassLoader() {
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        InputStream is = this.getResourceAsStream(name + CLASS_FILE_SUFFIX);
        if (is == null) {
            throw new ClassNotFoundException("Class '" + name + "' not found in resources!");
        }

        // 读取字节码文件
        int fileLen;
        try {
            fileLen = is.available();
            byte[] xlassFileBytes = new byte[fileLen];
            is.read(xlassFileBytes);
            byte[] classBytes = decode(xlassFileBytes);
            return defineClass(name, classBytes, 0, classBytes.length);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("IO error occurs when trying to find class '" + name + "'!");
        }
        finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private byte[] decode(byte[] classBytes) {
        if (classBytes != null) {
            for (int i = 0; i < classBytes.length; i++) {
                byte classByte = (byte) (255 - classBytes[i]);
                classBytes[i] = classByte;
            }
        }
        return classBytes;
    }

}
